<script setup lang="ts">
import UQRCode from 'uqrcodejs'


interface Props {
  value?: string
  options?: any
}

const props = withDefaults(defineProps<Props>(), {
  value: '',
  options: () => { },
})

const loading = ref<boolean>(false)
const imageURL = ref<string>('')

watch(() => props, () => init(), { deep: true, immediate: true })

function init() {
  console.log(123);

  loading.value = true
  const options = {
    data: props.value || 'https://uqrcode.cn/doc/',
    size: 200,
    margin: 10,
    foregroundColor: '#000000',
    backgroundColor: '#FFFFFF',
    errorCorrectLevel: 2,
    foregroundImageSrc: '',
    ...props.options,
  }
  const qr = new UQRCode()
  qr.setOptions(options)
  qr.make()
  const drawModules = qr.getDrawModules()
  let dom = ''
  for (let i = 0; i < drawModules.length; i++) {
    const drawModule = drawModules[i]
    switch (drawModule.type) {
      case 'tile':
        /* 绘制小块 */
        dom += `<rect x="${drawModule.x}" y="${drawModule.y}" width="${drawModule.width}" height="${drawModule.height}" fill="${drawModule.color}" />`
        break
      case 'image':
        /* 绘制图像 */
        dom += `<image href="${drawModule.imageSrc}" x="${drawModule.x}" y="${drawModule.y}" width="${drawModule.width}" height="${drawModule.height}" />`
        break
    }
  }
  const html = `<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1">${dom}</svg>`
  const blob = new Blob([html], { type: 'image/svg+xml' })
  imageURL.value = URL.createObjectURL(blob)
  loading.value = false
}

onUnmounted(() => {
  URL.revokeObjectURL(imageURL.value)
})
</script>

<template>
  <div class="h-200px w-200px rounded bg-white shadow">
    <el-image v-loading="loading" :src="imageURL" class="block h-full w-full" />
  </div>
</template>
